<template>
  <div class="order-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="我的订单" left-arrow fixed class="nav-bar"
      :style="{ background: 'linear-gradient(135deg, #FFFFFF 0%, #F8FAFF 100%)' }" @click-left="onClickLeft" style="max-width: 512px;" />
    <!-- <van-nav-bar title="标题" left-text="返回" left-arrow  /> -->


    <!-- 状态标签栏 -->
    <van-tabs v-model:active="active" @click-tab="onClickTab">
      <van-tab v-for="item in tabs" :title="item.title" :name="item.name">
      </van-tab>
    </van-tabs>
    <!-- <div class="tab-container" style="width: 100%;">
      <van-tabs v-model:active="activeTab" swipeable class="status-tabs" line-width="40" line-height="4"
        :ellipsis="false" :border="false">
        <van-tab v-for="tab in tabs" :key="tab.name" :title="tab.title" :name="tab.name" class="status-tab">
          <template #title>
            <div class="tab-content">
              <span class="status-dot" :style="{ backgroundColor: tab.color }"></span>
              {{ tab.title }}
            </div>
          </template>
</van-tab>
</van-tabs>
</div> -->

    <!-- 订单列表 -->
    <div class="order-list-container">
      <van-list class="order-list">
        <div v-for="(order, index) in orders" :key="order.id" class="order-card">
          <van-card class="order-item" :thumb="order.productList[0].goods_list.shopUrl_text"
            :thumb-link="order.productList[0].goods_list.shopUrl_text" @click="goToDetail(order.id, order.status)">

            <template #title>
              <div class="order-header">
                <span class="order-status" :style="{ color: order.statusColor }">
                  {{ order.statusText }}
                </span>
                <span class="order-time">{{ order.createtime }}</span>
              </div>
            </template>

            <template #tags>
              <div class="goods-preview">
                <!-- <van-image
                  :src="order.goodsList[0]?.goodsImg"
                  width="64"
                  height="64"
                  fit="cover"
                  class="primary-goods-thumb"
                /> -->
                <div class="goods-info">
                  <div class="goods-title">{{ order.productList[0].goods_list.name }}</div>

                  <!-- <div class="goods-specs">
                    {{ order.goodsList[0]?.color }} | {{ order.goodsList[0]?.size }}
                  </div> -->
                </div>
                <!-- <div class="goods-count">×{{ order.pronum }}</div> -->

              </div>
            </template>

            <template #footer>
              <div style="font-size: 10px; color: gray;">订单号:{{ order.code }}</div>
              <div class="order-footer">

                <div class="price-section">
                  <span class="price-symbol">¥</span>
                  <span class="main-price">{{ order.amount }}</span>

                  <!-- <span v-if="order.discountAmount > 0" class="discount-tag">
                    省{{ order.discountAmount.toFixed(2) }}
                  </span> -->
                </div>
                <van-button v-if="order.status == -2" size="small" type="primary" round class="action-btn"
                  @click.stop="handlePay(order.id, order.status)">
                  立即支付
                </van-button>
                <van-button v-if="order.status == 2" size="small" type="info" round class="action-btn"
                  @click.stop="checkLogistics(order.id)">
                  查看物流
                </van-button>
                <van-button v-if="order.status == 3" size="small" type="warning" round class="action-btn"
                  @click.stop="evaluateOrder(order.id)">
                  评价商品
                </van-button>
                <van-button v-if="order.status == -1" size="small" type="danger" round class="action-btn"
                  @click.stop="checkRefund(order.id)">
                  退款进度
                </van-button>
              </div>
            </template>
          </van-card>
        </div>
      </van-list>
    </div>
    <!-- 物流详情 -->
    <!-- <van-steps v-if="exStatus==1" direction="vertical" :active="0">
      <van-step>
        <h3>【城市】物流状态1</h3>
        <p>2016-07-12 12:40</p>
      </van-step>
      <van-step>
        <h3>【城市】物流状态2</h3>
        <p>2016-07-11 10:00</p>
      </van-step>
      <van-step>
        <h3>快件已发货</h3>
        <p>2016-07-10 09:30</p>
      </van-step>
    </van-steps> -->

    <!-- 空状态 -->
    <van-empty v-if="!orders.length" image="https://fastly.picsum.photos/200/200?seed=empty" description="暂无相关订单"
      class="empty-state">
      <template #image>
        <div class="empty-illustration">
          📦
          <div class="empty-text">空空如也~</div>
        </div>
      </template>
    </van-empty>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { Empty, showToast } from 'vant';
import { POST } from '../services/request';
import { useRoute, useRouter } from 'vue-router';

const router = new useRouter();
const route = new useRoute();

const queryStatus = ref(route.query.status);
// console.log(queryStatus.value,'queryStatus');


const exStatus = ref(0)
const exFlag = ref(false)

// 状态标签配置
const active = ref('0');
if(queryStatus){
  active.value = queryStatus.value
}

// 订单列表
const orders = ref([]);

const tabs = [
  { title: '全部', name: '0', color: '#718096' },
  { title: '已支付', name: '1', color: '#2A6F97' },
  { title: '已发货', name: '2', color: '#006400' },
  { title: '已收货', name: '3', color: '#D97706' },
  { title: '退货', name: '-1', color: '#C9184A' },
  { title: '未支付', name: '-2', color: '#E63946' },
];

const userData = JSON.parse(localStorage.getItem('LoginUser'));
// console.log(userData.id);



onMounted(async () => {
  await getOrders();
})

// 查询所有订单
const getOrders = async () => {
  const getOrdersRes = await POST({
    url: '/Order/getOrders',
    params: {
      uid: userData.id,
      status: queryStatus.value
    }
  })
  if (getOrdersRes.code === 1) {
    console.log(getOrdersRes.data);
    orders.value = [];
    const ordersData = getOrdersRes.data.map((item) => {
      // console.log(item);
      item.createtime = formatTimestamp(item.createtime)
      switch (item.status) {
        case '-2':
          item.statusColor = '#E63946'
          item.statusText = '待支付'
          break;
        case '1':
          item.statusColor = '#2A6F97'
          item.statusText = '已支付'
          break;
        case '2':
          item.statusColor = '#006400'
          item.statusText = '已发货'
          break;
        case '3':
          item.statusColor = '#D97706'
          item.statusText = '已收货'
          break;
        case '-1':
          item.statusColor = '#C9184A'
          item.statusText = '退货中'
          break;
      }
      orders.value.push(item)
    })
  }
}

// 返回上级
const onClickLeft = () => history.back();

// 点击标签页，传状态值进行分类
const onClickTab = async (stas) => {
  // console.log(stas.name);
  // if(!Empty(queryStatus.value)){
  //   stas.name = queryStatus.value
  // }
  const getOrdersClassRes = await POST({
    url: '/Order/getOrders',
    params: {
      uid: userData.id,
      status: stas.name
    }
  })
  if (getOrdersClassRes.code === 1) {
    orders.value = [];
    const ordersData = getOrdersClassRes.data.map((item) => {
      // console.log(item);
      item.createtime = formatTimestamp(item.createtime)
      switch (item.status) {
        case '-2':
          item.statusColor = '#E63946'
          item.statusText = '待支付'
          break;
        case '1':
          item.statusColor = '#2A6F97'
          item.statusText = '已支付'
          break;
        case '2':
          item.statusColor = '#006400'
          item.statusText = '已发货'
          break;
        case '3':
          item.statusColor = '#D97706'
          item.statusText = '已收货'
          break;
        case '-1':
          item.statusColor = '#C9184A'
          item.statusText = '退货中'
          break;

      }
      orders.value.push(item)
    })

    // console.log(orders.value,'orders.value');
    
  }
}


const formatTimestamp = (timestamp) => {
  // 处理秒级时间戳
  if (timestamp.toString().length === 10) {
    timestamp = timestamp * 1000;
  }

  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 时间格式化
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes()}`;
};

// 事件处理
// 跳转订单详情
const goToDetail = (orderId, status) => {
  // console.log(orderId,status);
  router.push({
    name: 'orderInfo',
    query: {
      orderId: orderId,
      uid: userData.id,
      status: status
    }
  });

};

// 立即支付
const handlePay = async (orderId, status) => {
  router.push({
    name: 'orderInfo',
    query: {
      orderId: orderId,
      uid: userData.id,
      status: status
    }
  });
  // showToast(`支付订单 ${orderId}`);
  // console.log(orderId);
  // console.log(orderId,status);
  // const payRes = await POST({
  //   url:'',
  //   params:{

  //   }
  // })

};

const checkLogistics = (orderId) => {
  router.push({
    path:'/expressInfo',
    query:{
      orderId
    }
  })
  // showToast(`查看订单 ${orderId} 物流`);
  // exFlag.value =! exFlag.value;
  // if(exFlag.value==true){
  //   exStatus.value = 1
  // }else{
  //   exStatus.value = 0
  // }

};

const evaluateOrder = (orderId) => {
  showToast(`评价订单 ${orderId}`);
};

const checkRefund = (orderId) => {
  showToast(`查看订单 ${orderId} 退款进度`);
};
</script>



<style scoped>
.tab-container {
  position: fixed !important;
  top: 45px !important;
}

/* .order-list-container {
  padding-top: 48px;
} */

.order-page {
  background: #F8F9FF;
  min-height: 100vh;
  padding-top: 56px;
}

/* 导航栏样式 */
.nav-bar {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.nav-bar ::v-deep .van-nav-bar__title {
  font-weight: 600;
  font-size: 18px;
  color: #2D3748;
}

/* 状态标签栏 */
.tab-container {
  position: sticky;
  top: 56px;
  z-index: 2;
  background: white;
  padding: 8px 0;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.03);
}

.status-tabs {
  ::v-deep .van-tabs__nav {
    padding: 0 12px;
  }

  ::v-deep .van-tab {
    flex: 1;
    min-width: auto;
    padding: 0 8px;
  }
}

.status-tab {
  .tab-content {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    border-radius: 20px;
    transition: all 0.3s;
  }

  .status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    flex-shrink: 0;
  }
}

/* 订单卡片 */
.order-item {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  margin: 12px;
  transition: transform 0.3s;

  &:active {
    transform: scale(0.99);
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.order-status {
  font-weight: 500;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 12px;
  background: rgba(230, 57, 70, 0.1);
}

.order-time {
  font-size: 12px;
  color: #718096;
}

/* 商品预览 */
.goods-preview {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  padding: 8px 0;
}

.primary-goods-thumb {
  flex-shrink: 0;
  border-radius: 12px;
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.goods-info {
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.goods-title {
  font-size: 14px;
  font-weight: 500;
  color: #2D3748;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.goods-specs {
  font-size: 12px;
  color: #718096;
  background: #F7FAFC;
  padding: 2px 6px;
  border-radius: 6px;
  display: inline-block;
}

.goods-count {
  flex-shrink: 0;
  font-size: 14px;
  color: #A0AEC0;
  font-weight: 500;
  margin-left: 12px;
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #F5F7FA;
}

.price-section {
  display: flex;
  align-items: baseline;
  gap: 4px;

  .price-symbol {
    font-size: 12px;
    color: #E63946;
  }

  .main-price {
    font-size: 20px;
    font-weight: 600;
    color: #E63946;
    letter-spacing: -0.5px;
  }

  .discount-tag {
    font-size: 12px;
    color: #38A169;
    background: #F0FFF4;
    padding: 2px 6px;
    border-radius: 6px;
  }
}

.action-btn {
  min-width: 72px;
  height: 28px;
  font-size: 12px;
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  margin-top: 40px;
}

.empty-illustration {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 64px;
  color: #CBD5E0;

  .empty-text {
    font-size: 16px;
    margin-top: 12px;
    color: #A0AEC0;
  }
}
</style>